package fr.alesia.deepstack.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.alesia.deepstack.bean.Player;
import fr.alesia.deepstack.bean.Ranking;
import fr.alesia.deepstack.bean.Tournament;
import fr.alesia.deepstack.data.PlayerDao;
import fr.alesia.deepstack.data.RankingDao;
import fr.alesia.deepstack.data.TournamentDao;
import fr.alesia.deepstack.factory.BeanFactory;
import fr.alesia.deepstack.factory.DaoFactory;

@SuppressWarnings("serial")
public class LobbyServlet extends HttpServlet {
	
	@Override
	protected void doGet(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		
		ServletContext context = this.getServletContext();
		PlayerDao playerDao = DaoFactory.getPlayerDao();
		String[] ids = request.getParameterValues("challengers");
		
		if(ids == null || ids.length < 2){
		
			Set<Player> players = playerDao.findAll();
			request.setAttribute("players", players);
			RequestDispatcher dispatcher = context.getRequestDispatcher("/webapp/page/private/logging-in.jsp");
			dispatcher.forward(request, response);
		}
		else{
			
			Set<Player> challengers = new HashSet<Player>(ids.length);
			for (String id : ids) {
				
				Player challenger = playerDao.find(id);
				challengers.add(challenger);
			}
			TournamentDao tournamentDao = DaoFactory.getTournamentDao();
			Tournament tournament = BeanFactory.createTournament(new Date());
			tournamentDao.insert(tournament);
			
			RankingDao rankingDao = DaoFactory.getRankingDao();
			for (Player player : challengers) {
				Ranking ranking = BeanFactory.createRanking(player, tournament, 0);
				rankingDao.insert(ranking);
			}
			
			request.setAttribute("tournament", tournament);
			request.setAttribute("challengers", challengers);
			RequestDispatcher dispatcher = context.getRequestDispatcher("/webapp/page/private/tournament.jsp");
			dispatcher.forward(request, response);
		}
	}

	@Override
	protected void doPost (
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		
		this.doGet(request, response);
	}
}
